package com.mall.malllibrary.net.callback

import android.os.Handler
import com.mall.malllibrary.global.GlobalKeys
import com.mall.malllibrary.global.Mall
import com.mall.malllibrary.ui.loader.LoaderStyle
import com.mall.malllibrary.ui.loader.MallLoader
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


// 使用主构造函数的简易写法，
class RequestCallbacks(
    private val success: ISuccess?,
    private val failure: IFailure?,
    private val error: IError?,
    private val complete: IComplete?,
    private val request: IRequest?,
    private val loaderStyle: LoaderStyle?,
) : Callback<String> { // 继承自retrofit2 包下面的callback并重写对应的方法
    override fun onResponse(call: Call<String>, rsp: Response<String>) {

        if (rsp.isSuccessful) {
            if (success!= null && rsp.body() != null) {
                success.onSuccess(rsp.body()!!)
            }
        } else {
            error?.onError(rsp.code(), rsp.message())
        }
        onRequestFinish()
    }
    // 请求结束，去掉弹窗
    private fun onRequestFinish(){
        val delayd = Mall.getConfiguration<Long>(GlobalKeys.LOADER_DELAYED)
        if (loaderStyle!=null){
           HANDLER.postDelayed({MallLoader.stopLoading()}, delayd)
        }
    }

    companion object{
        private val HANDLER : Handler = Mall.getConfiguration(GlobalKeys.HANDLER)
    }

    override fun onFailure(p0: Call<String>, p1: Throwable) {
        failure?.onFailure()
        request?.onRequestEnd()
    }

}